<?php


namespace App\Http\Controllers\Sale;


use App\Http\Controllers\Sale\BaseController;
use App\Models\SaleUser;
use App\Models\SaleBillLog;
use App\Models\SaleLog;
use App\Models\ShopSms;

use App\Models\ShopWithdrawal;

use App\Services\CommonService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class WithdrawalController extends BaseController
// class WithdrawalController
{
    /**
     * 提现列表
     * @param Request $request
     * @return false|string
     */
    public function withdrawalList(Request $request){
        $payeeName = $request->input('payeeName','');
        $payeeAccount = $request->input('payeeAccount','');
        $arrivalTime = $request->input('arrivalTime','');
        $status = $request->input('status','');
        $type = $request->input('type',2);
        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',10);
        if($type == 1){
            
        }else{
            //提现明细
            $where[] = ['w.sale_user_id',$this->users['sale_user_id']];
            if($payeeName){
                $where[] = ['w.payee_name','like','%'.$payeeName.'%'];
            }
            if($payeeAccount){
                $where[] = ['w.payee_account','like','%'.$payeeAccount.'%'];
            }
            if($status){
                $where[] = ['w.status',$status];
            }
            if($arrivalTime){
                $arrivalTime = explode('~', $arrivalTime);
                $where[] = ['w.apply_time','>=',$arrivalTime[0]];
                $where[] = ['w.apply_time','<',$arrivalTime[1]];
            }
            $list = ShopWithdrawal::from('sp_shop_withdrawal as w')
                ->select('w.id','w.sale_user_id','w.withdrawal_amount','w.payee_name','w.payee_account','w.alipay_trade_no','w.out_biz_no','w.out_biz_no'
                    ,'w.pay_type','w.status','w.refuse_reason','w.apply_time','w.check_time','w.admin_id','w.arrival_time'
                )
                ->where($where)
                ->orderBy('w.id','desc')
                ->paginate($pageSize);
        }
        $list = obToArray($list);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$list);
        
    }

    /**
     * 申请提现
     * @param Request $request
     * @return false|string
     */
    public function withdrawalApply(Request $request){
        try{
            
            $amount = $request->input('amount','');
            if(!$amount){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
            }
            $where = [];
            
            $where[] = ['sale_user_id',$this->users['sale_user_id']];
            
            $sale = SaleUser::GetSaleUser($where);
            
            if(!$sale['payeename'] || !$sale['alipayaccount']){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未设置提现账户');
            }
            if (!preg_match('/^[0-9]+(.[0-9]{1,2})?$/', $amount)) {
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'提现金额错误');
            }
            
            if($amount < ShopWithdrawal::WITHDRAWAL_AMOUNT_LIMIT){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'提现金额不能低于'.ShopWithdrawal::WITHDRAWAL_AMOUNT_LIMIT.'元');
            }
            
            $balance = SaleUser::where(['sale_user_id'=>$this->users['sale_user_id']])->value('balance');
            if($amount > $balance){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'账户余额不足');
            }
            
            $apply_time = ShopWithdrawal::where(['sale_user_id'=>$this->users['sale_user_id'],'status'=>ShopWithdrawal::WITHDRAWAL_STATUS_REVIEWED])->orderBy('id','desc')->value('apply_time');
            
            if(strtotime($apply_time) == time()){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请稍后再试');
            }
            
            DB::beginTransaction();
            
            $data = [
                'member_id'=>0,
                'sale_user_id'=>$this->users['sale_user_id'],
                'withdrawal_amount'=>$amount,
                'payee_name'=>$sale['payeename'],
                'payee_account'=>$sale['alipayaccount'],
                'apply_time'=>dateFormat(time()),
                'apply_admin_id'=>$this->users['id'],
            ];
            
            $res = ShopWithdrawal::insertGetId($data);
            
            if($res){
                
                $sale_bill_data = array(
                    'sale_user_id' => $this->users['sale_user_id'],
                    'money' => $amount,
                    'balance_before' => $sale['balance'],
                    'balance_after' => $sale['balance']  - $amount,
                    'type' => SaleBillLog::MONEY_PUT,
                    'content' => '分销商'.$this->users['username'].'申请提现',
                    'remark' => '',
                );
                // dd(2);
                SaleBillLog::setBillList($sale_bill_data);
                
                SaleUser::where(['sale_user_id'=>$this->users['sale_user_id']])->increment('balance_drawal',$amount);
                SaleUser::where(['sale_user_id'=>$this->users['sale_user_id']])->decrement('balance',$amount);
                
                $data_log = [];
                $data_log['sale_user_id'] = $this->users['sale_user_id'];
                $data_log['user_id'] = $this->users['id'];
                $data_log['content'] = '分销商'.$this->users['username'].'申请提现';
                $data_log['remark'] = '';
                SaleLog::addLog($data_log);
                
                //发短信
                //用户名   申请时间  申请金额  发送电话
                $time = date('Y-m-d H:i:s');
                ShopSms::withdrawalApply($this->users['username'],$time,$amount,$this->users['mobile']);
                
                
                DB::commit();
                return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'申请成功',['withdrawal_id'=>$res]);
            }else{
                DB::rollBack();
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'申请失败');
            }
        }catch (\Exception $exception){
            DB::rollBack();
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'申请失败');
        }
    }

    /**
     * 提现信息
     * @param Request $request
     * @return false|string
     */
    public function withdrawalInfo(Request $request){
        $withdrawal_id = $request->input('withdrawal_id','');
        if(!$withdrawal_id){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }
        // dd($this->users);
        //'sale_user_id',$this->users['sale_user_id']
        $sale_user_id = $this->users['sale_user_id'];
        $where = [];
        $where[] = ['sale_user_id',$sale_user_id];
        $sale = SaleUser::GetSaleUser($where);
        $data['balance'] = $sale['balance'];
        $data['balance_drawal'] = $sale['balance_drawal'];
        $withdrawal = ShopWithdrawal::where([['id',$withdrawal_id],['sale_user_id',$sale_user_id]])->select('withdrawal_amount','pay_type','payee_name','payee_account','apply_time','status','refuse_reason','check_time')->first();
        $withdrawal = obToArray($withdrawal);
        if(!empty($withdrawal)){
            $withdrawal['status_name'] = ShopWithdrawal::WITHDRAWAL_STATUS_LIST[$withdrawal['status']];
            $withdrawal['pay_type'] = ShopWithdrawal::WITHDRAWAL_TYPE_LIST[$withdrawal['pay_type']];
        }
        $data['withdrawal_info'] = $withdrawal;

        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }
    
    /**
     * 获取收款账户信息
     * @param Request $request
     * @return false|string
     */
    public function getPayeeInfo(Request $request){
        $sale_user_id = $this->users['sale_user_id'];
        $where = [];
        $where[] = ['sale_user_id',$sale_user_id];
        $sale = SaleUser::GetSaleUser($where);
        
        $data['payeename'] = $sale['payeename'];
        $data['alipayaccount'] = $sale['alipayaccount'];
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }

}
